/*
 * Created on 2006-10-18
 *
 */
package com.shop.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.net.URL;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.util.Collection;
import java.util.Iterator;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * @author bomb
 *  
 */
public class StringUtil {
    public static String NEW_PAGE = "NEWPAGE";

    public static String TAG_START = "TAGSTART";

    public static String TAG_END = "TAGEND";

    public static String context = "";

    public static DecimalFormat df = new DecimalFormat("0.##");
    public static DecimalFormat df2 = new DecimalFormat("0.#");

    public static String encodeUrl(String url) {
        try {
            return URLEncoder.encode(url, "utf-8");
        } catch (Exception e) {
            return "";
        }
    }

    public static String getRequestURL(HttpServletRequest request) {
        String queryString = request.getQueryString();
        if (queryString == null)
            return request.getRequestURI();
        else
            return request.getRequestURI() + "?" + queryString;
    }

    public static int toId(String s) {
        try {
            return Integer.parseInt(s);
        } catch (Exception e) {
            return 0;
        }
    }

    public static int[] toIds(String s) {
        try {
        	if(StringUtil.isNull(s)){
        		return new int[0];
        	}
        	String[] ss = s.split(",");
        	int[] result = new int[ss.length];
        	for(int i=0; i<ss.length; i++){
        		result[i] = StringUtil.toInt(ss[i]);
        	}
            return result;
        } catch (Exception e) {
            return new int[0];
        }
    }

    public static float toFloat(String s) {
        try {
            return Float.parseFloat(s);
        } catch (Exception e) {
            return 0;
        }
    }
    public static String toHtml(String src) {
        if (src == null)
            return "";

        src = src.replaceAll("<", "&lt;");
        src = src.replaceAll(">", "&gt;");
        src = src.replaceAll("\r\n", "<br/>");
        src = src.replaceAll("\n", "<br/>");        

//        Matcher m = p.matcher(src);
//        while (m.find()) {
//            String s = m.group(1);
//            s = "<a href=\"" + s + "\" target=_blank>" + "<img src=\"" + s
//                    + "\" width=\"400\" border=0 alt=\"点击查看大图\"/></a>";
//            src = m.replaceFirst(s);
//            m = p.matcher(src);
//        }
        return src;
    }
    public static String convertNull(String s) {
        if (s == null) {
            return "";
        } else {
            return s;
        }
    }

    public static String cutString(String s, int count) {
        if (s == null) {
            return s;
        }
        if (s.length() < count) {
            return s;
        }
        s = s.substring(0, count);
        return s;
    }

    public static String trim(String s) {
        if (s == null) {
            return s;
        }
        s = s.replaceAll("\r\n", "");
        s = s.replaceAll("\n", "");
        s = s.replaceAll(" ", "");
        return s;
    }

    public static String getURLContent(String url) {
        try {
            URL u = new URL(url);
            BufferedReader br = new BufferedReader(new InputStreamReader(u
                    .openStream()));
            String str = br.readLine();
            StringBuffer sb = new StringBuffer();
            while (str != null) {
                sb.append(str);
                str = br.readLine();
            }
            return sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static int toInt(String s) {
        try {
            return Integer.parseInt(s);
        } catch (Exception e) {
            return -1;
        }
    }
    
    public static int toInt(String s,int def) {
        try {
            return Integer.parseInt(s);
        } catch (Exception e) {
            return def;
        }
    }

    public static boolean isLetterOrNumber(String s) {
        if (s == null) {
            return false;
        } else {
            for (int i = 0; i < s.length(); i++) {
                int a = s.charAt(i);
                if ((a >= 48 && a <= 57) || (a >= 65 && a <= 90)
                        || (a >= 97 && a <= 122)) {
                } else {
                    return false;
                }
            }
        }
        return true;
    }

    public static boolean isMobile(String s) {
        if (s == null) {
            return false;
        }

        if (!s.startsWith("13") && !s.startsWith("15") && !s.startsWith("18")) {
            return false;
        }

        if (s.length() != 11) {
            return false;
        }

        try {
            Long.parseLong(s);
        } catch (NumberFormatException e) {
            return false;
        }
        return true;
    }

    public static String toWml(String src) {
        if (src == null)
            return "";

        src = src.replaceAll("&", "&amp;");
        src = src.replaceAll("\\$", "");
        src = src.replaceAll("¤", "O");
        src = src.replaceAll("<", "&lt;");
        src = src.replaceAll(">", "&gt;");
        src = src.replaceAll("\r\n", "<br/>");
        src = src.replaceAll("\n", "<br/>");
        src = src.replaceAll("", "");

        return src;
    }

    public static String toWml2(String src) {
        if (src == null)
            return "";
        src = src.replaceAll("&", "&amp;");
        src = src.replaceAll("\\$", "");
        src = src.replaceAll("¤", "O");
        src = src.replaceAll("<", "&lt;");
        src = src.replaceAll(">", "&gt;");
        src = src.replaceAll("\r\n", "<br/>");
        src = src.replaceAll("\n", "<br/>");
        src = src.replaceAll("", "");
        src = src.replace("\\'", "'");
        src = src.replaceAll("\"", "&#34;");
        return src;
    }

    public static void sendRedirect(String link, HttpServletRequest request,
            HttpServletResponse response) {

        try {
            response.sendRedirect(response.encodeRedirectURL(link));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public static String dealLink(String link, HttpServletRequest request,
            HttpServletResponse response) {
        if (link == null) {
            return link;
        }

        // String domain = request.getServerName();
        // if (link.startsWith("/")) {
        // link = "http://" + domain + response.encodeURL(link);
        // }
        if (link.indexOf("uuniq") == -1) {
            if (link.indexOf("?") != -1) {
                link += "&uuniq=" + getUnique();
            } else {
                link += "?uuniq=" + getUnique();
            }
        }
        // link = link.replaceAll("&", "&amp;");

        return link;// response.encodeURL(link);
    }

    public static String dealRedirectLink(String link,
            HttpServletRequest request, HttpServletResponse response) {
        if (link == null) {
            return link;
        }

        String domain = request.getServerName();
        link = "http://" + domain + link;
        if (link.indexOf("?") != -1) {
            link += "&uuniq=" + getUnique();
        } else {
            link += "?uuniq=" + getUnique();
        }

        return response.encodeURL(link);
    }

    public static String getUnique() {
        Random rand = new Random();
        return System.currentTimeMillis() + "" + rand.nextInt(10) + ""
                + rand.nextInt(10) + "" + rand.nextInt(10);
    }

    public static boolean isNull(String s) {
        if (s == null) {
            return true;
        }
        if ("".equals(s)) {
            return true;
        }
        return false;
    }

    public static boolean isChinese(char c) {
        if (c >= '\u4E00' && c <= '\u9FA5') {
            return true;
        }
        return false;
    }

    public static boolean isLetter(char c) {
        if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
            return true;
        }
        return false;
    }

    public static boolean isNumber(char c) {
        if (c >= '0' && c <= '9') {
            return true;
        }
        return false;
    }

    public static boolean isNumber(String s) {
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (!isNumber(c))
                return false;
        }
        return true;
    }

    public static boolean isChineseOrLetter(String s) {
        if (s == null) {
            return false;
        }

        char[] cs = s.toCharArray();
        for (int i = 0; i < cs.length; i++) {
            if (!isChinese(cs[i]) && !isLetter(cs[i])) {
                return false;
            }
        }

        return true;
    }

    public static String dealParam(String param) {
        if (param == null) {
            return param;
        }

        // param = param.replaceAll("'", "\"");
        param = param.replace("\\", "\\\\");
        param = param.replace("'", "\\'");
        param = param.trim();
        return param;
    }

    public static String toSql(String src) {
    	if(src==null || src.length()<1) return src;
        src = src.replace("\\", "\\\\");
        src = src.replace("'", "\\'");
        return src;
    }

    // 用于 like '??'
    public static String toSqlLike(String src) {
    	if(src==null || src.length()<1) return src;
        src = src.replace("\\", "\\\\");
        src = src.replace("'", "\\'");
        src = src.replace("%", "\\%");
        src = src.replace("_", "\\_");
        return src;
    }

    
    static Pattern p = Pattern.compile("productImage/(.*?)\"");
    

   

    public static String toRegex(String src) {
        if (src == null)
            return "";

        src = src.replaceAll("&", "&amp;");
        src = src.replaceAll("\\$", "");
        src = src.replaceAll("¤", "O");
        src = src.replaceAll("<", "&lt;");
        src = src.replaceAll(">", "&gt;");
        src = src.replaceAll("\r\n", "<br/>");
        src = src.replaceAll("\n", "<br/>");
        src = src.replaceAll("", "");
        src = src.replaceAll("\\.", "");
        src = src.replaceAll("\\*", "");
        src = src.replaceAll("\\%", "");

        return src;
    }

    public static String formatPrice(float price) {
        /*
         * if((price - (int)price) >= 0.5 ){ price = (int)price + 1; }
         */
        return StringUtil.df.format(price);
    }

    public static String formatPrice2(float price) {
        /*
         * if((price - (int)price) >= 0.5 ){ price = (int)price + 1; }
         */
        return StringUtil.df2.format(price);
    }

    public static float formatFloat(float f) {
        int b = 100;
        float temp = (int) (b * f);
        return temp / b;
    }


    public static String noEnter(String src) {
        if (src == null)
            return src;
        src = src.replace("　", "");
        src = removeSpecialAsc(src);
        return src;

    }

    public static String removeSpecialAsc(String str) {
        if (str == null)
            return str;
        str = wapUnicode(str);
        StringBuilder sb = new StringBuilder(str.length());
        char[] cs = str.toCharArray();
        for (int i = 0; i < cs.length; i++) {
            if (isChinese(cs[i]) || cs[i] > 32)
                sb.append(cs[i]);
        }
        return sb.toString();
    }

    // 替换类似&#nnnnn;和&#x83B7;等格式
    protected static int pGroup = 1;

    protected static Pattern pattern = Pattern
            .compile("&#([0-9]{3,5}|x[0-9A-F]{3,4});");

    public static String wapUnicode(String content) {
        if (content == null)
            return null;
        Matcher m = pattern.matcher(content);
        StringBuilder sb = new StringBuilder(content.length());
        int pos = 0;
        String c = null;
        while (m.find()) {
            sb.append(content.substring(pos, m.start(0)));
            c = m.group(pGroup);
            int c2 = 0;
            if (c.startsWith("x")) {
                c2 = hexToInt(c.substring(1));
            } else {
                c2 = toInt(c);
            }
            if (c2 > 256)
                sb.append((char) c2);
            pos = m.end(0);
        }
        sb.append(content.substring(pos));
        return sb.toString();
    }

    public static int hexToInt(String s) {
        try {
            return Integer.parseInt(s, 16);
        } catch (NumberFormatException e) {
            return -1;
        }
    }

    /**
     * 作者：李北金
     * 
     * 创建日期：2008-1-18
     * 
     * 说明：返回0-9,a-z,A-Z，用于生成随机代码
     * 
     * 参数及返回值说明：
     * 
     * index 范围是0-61
     * 
     * 0-9: 0-9
     * 
     * 10-35: a-z
     * 
     * 36-61: A-Z
     * 
     * @param index
     * @return
     */
    public static char getChar(int index) {
        if (index >= 0 && index <= 9) {
            return (char) ('0' + index);
        }
        if (index >= 10 && index <= 35) {
            return (char) ('a' + (index - 10));
        }
        if (index >= 36 && index <= 61) {
            return (char) ('A' + (index - 36));
        }
        return 'a';
    }

    public static String array2String(String[] strs, String split) {
        if (strs == null || strs.length == 0) {
            return "";
        }
        StringBuilder builder = new StringBuilder(strs.length * 10);
        for (int i = 0; i < strs.length; i++) {
            if (i != 0) {
                builder.append(split);
            }
            builder.append(strs[i]);
        }
        return builder.toString();
    }

    /**
     * 作者：曹续
     * 
     * 创建时间：2009-9-3
     * 
     * 补位左填充
     * 
     * 参数及返回值说明：
     * 
     * @param input
     * @param c
     * @param length
     * @return
     */
    public static String padLeft(String input, char c, int length) {
        String output = input;
        while (output.length() < length) {
            output = c + output;
        }
        return output;
    }

    /**
     * 作者：曹续
     * 
     * 创建时间：2009-9-7
     * 
     * 返回页码数字 从1开始
     * 
     * 参数及返回值说明：
     * 
     * @param s
     * @return
     */
    public static int toPageNo(String s) {
        try {
            return Integer.parseInt(s);
        } catch (Exception e) {
            return 1;
        }
    }

    public static boolean toBoolean(String s) {
        try {
            return Boolean.getBoolean(s);
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 作者：曹续
     * 
     * 创建时间：2009-9-10
     * 
     * 判断是否是合法银行卡号
     * 
     * 参数及返回值说明：
     * 
     * @param s
     * @return
     */
    public static boolean isCardId(String s) {
        try {
            if (s.length() < 12)
                return false;
            for (int i = 0; i < s.length(); i++) {
                if (!StringUtil.isNumber(s.charAt(i))) {
                    return false;
                }
            }
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public static boolean legalIDCardNo(String idCardNo) {
        boolean legal = false;
        if (idCardNo.length() == 15) {
            int year = Integer.parseInt(idCardNo.substring(6, 8));
            String regex = "^[1-9][0-9]{5}[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|1[0-9]|2[0-8]))[0-9]{3}$";
            if (year % 4 == 0 || (year % 100 == 0 && year % 4 == 0)) {
                regex = "^[1-9][0-9]{5}[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}$";
            }
            if (idCardNo.matches(regex)) {
                legal = true;
            }
        } else if (idCardNo.length() == 18) {
            int year = Integer.parseInt(idCardNo.substring(6, 10));
            String regex = "^[1-9][0-9]{5}19[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|1[0-9]|2[0-8]))[0-9]{3}[0-9Xx]$";
            if (year % 4 == 0 || (year % 100 == 0 && year % 4 == 0)) {
                regex = "^[1-9][0-9]{5}19[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}[0-9Xx]$";
            }
            if (idCardNo.matches(regex)) {
                legal = true;
            }
        }
        return legal;
        //		String[] idCardArray = idCardNo.split("");
        //		int s=(Integer.parseInt(idCardArray[1]) +
        // Integer.parseInt(idCardArray[11])) * 7
        //			+ (Integer.parseInt(idCardArray[2]) +
        // Integer.parseInt(idCardArray[12])) * 9
        //			+ (Integer.parseInt(idCardArray[3]) +
        // Integer.parseInt(idCardArray[13])) * 10
        //			+ (Integer.parseInt(idCardArray[4]) +
        // Integer.parseInt(idCardArray[14])) * 5
        //			+ (Integer.parseInt(idCardArray[5]) +
        // Integer.parseInt(idCardArray[15])) * 8
        //			+ (Integer.parseInt(idCardArray[6]) +
        // Integer.parseInt(idCardArray[16])) * 4
        //			+ (Integer.parseInt(idCardArray[7]) +
        // Integer.parseInt(idCardArray[17])) * 2
        //			+ Integer.parseInt(idCardArray[8]) * 1
        //			+ Integer.parseInt(idCardArray[9]) * 6
        //			+ Integer.parseInt(idCardArray[10]) * 3 ;
        //		int y = s %11 ;
        //		String flag = "10X98765432" ;
        //		String m = flag.substring(y,y+1);
        //		if(m.equals(idCardArray[18])){
        //			legal =true ;
        //		}
    }

    public static String convertNull(String s, String def) {
        if (s == null) {
            return def;
        } else {
            return s;
        }
    }


    public static String cutString(String s, int start, int length) {
        if (s == null || s.length() <= start) {
            return s;
        }
        if (s.length() < (start + length) || length < 1) {
            return s.substring(start, s.length());
        } else {
        	return s.substring(start, start + length);
        }
    }
    
    //获得指定长度的字符串,汉字作为两个字符处理
    public static String getLength(String str, int length) {
    	int charLength = 0;
		int cutLength = 0;
		boolean needCut = false;
		if(str != null && str.length()>0) {
			char[] cs = str.toCharArray();
			for (int i = 0; i < cs.length; i++) {
	           if (StringUtil.isChinese(cs[i])) {
	            	charLength += 2;
	           } else {
	            	charLength += 1;
	           }
	           cutLength += 1;
	           if(charLength>=length) {
	            	needCut = true;
	            	break;
	           }
		    }
		}
		if(needCut){
			str = str.substring(0,cutLength)+"...";
		}
		return str;
    }
    //处理火星文
    public static String dealString(String str) {
    	char[] HEX_TABLE = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
    	String result = "";
		char[] index = str.toCharArray();
		for(int i=0; i<index.length; i++){
			char c = index[i];
			if ((c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')){
				result += c;
			} else {
				result += "%";
				result += HEX_TABLE[(c >> 4) & 0x0f];
				result += HEX_TABLE[c & 0x0f];
			}
		}
		return result;
    }

    /**
     * 处理手机号码，只保留前三个后最后两个数字
     * @param cellphone
     * @return
     */
	public static String dealCellPhone(String cellphone) {
		return cellphone.substring(0, 3)+"******"+cellphone.substring(9, cellphone.length());
	}
	
	//异常信息输出转换
    public static String getExceptionInfo(Throwable t) {   
        StringWriter stringWriter= new StringWriter();   
        PrintWriter writer= new PrintWriter(stringWriter);   
        t.printStackTrace(writer);   
        StringBuffer buffer= stringWriter.getBuffer();   
        return buffer.toString();   
    }
    
	public static String outputObject(Object obj) throws IllegalArgumentException, IllegalAccessException {
		StringBuilder sb = new StringBuilder(128);
		if (obj != null) {
			Class c = obj.getClass();
			Field[] fs = c.getDeclaredFields();
			sb.append("<font color=green>");
			sb.append(obj.toString());
			sb.append("</font>--");
			sb.append(c.getName());
			sb.append("<br/>");

			for (int i = 0; i < fs.length; i++) {
				Field f = fs[i];
				int m = f.getModifiers();
				if (Modifier.isStatic(m))
					continue;
				f.setAccessible(true);
				sb.append(f.getName());
				sb.append("&nbsp;=&nbsp;<font color=red>");
				sb.append(f.get(obj));
				sb.append("</font>&nbsp;[");
				sb.append(f.getType().getSimpleName());
				sb.append("]<br/>");
			}
			if (obj instanceof Collection) {
				sb.append("<br/>");
				Collection cl = (Collection) obj;
				int limit = 20;
				Iterator iter = cl.iterator();
				while (iter.hasNext() && --limit > 0) {
					sb.append(outputObject(iter.next()));
				}
			}
			if (obj instanceof Object[]) {
				Object[] objs = (Object[]) obj;
				sb.append("<br/>");
				for (int i = 0; i < 20 && i < objs.length; i++) {
					sb.append(outputObject(objs[i]));
				}
			}
		}
		return sb.toString();
	}
}
